package com.zhang.redis.config;

import lombok.RequiredArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-11-30 15:56
 **/
@RequiredArgsConstructor
@AutoConfigureAfter(MyRedisConfig.class)
@Configuration
public class MyRedissonConfig {

    /**
     * 可以换成nacos配置读取
     */
    @Value("${spring.redis.cluster.nodes}")
    private String nodes;


    @Bean(destroyMethod = "shutdown", name = "stringRedisson")
    public RedissonClient setStringClient() {
        String[] split = getNodeAddress();
        Config config = new Config();
        config.useClusterServers()
                //3000毫秒扫描一次集群
                .setScanInterval(3000)
                .addNodeAddress(split);
        //序列化处理
        config.setCodec(new StringCodec());
        //redissonClient
        return Redisson.create(config);
    }

    @Bean(destroyMethod = "shutdown", name = "jsonRedisson")
    public RedissonClient setJsonClient() {
        String[] split = getNodeAddress();
        Config config = new Config();
        config.useClusterServers()
                //3000毫秒扫描一次集群
                .setScanInterval(3000)
                .addNodeAddress(split);
        //序列化处理
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }

    /**
     * 地址
     */
    private String[] getNodeAddress() {
        String[] split = nodes.split("\\,");
        for (int i = 0; i < split.length; i++) {
            split[i] = "redis://" + split[i];
        }
        return split;
    }
}
